package socket聊天;

import java.io.*;
import java.net.Socket;
import java.nio.Buffer;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    /**
     * socket封装了tcp协议的通讯细节，使得我们使用它可以与远端计算机连接
     * 并基于两条流（输入输出流），完成数据交换
     */
    private Socket socket;

    public Client(){
        //构造方法用来初始化客户端，建立连接
        try {
            System.out.println("正在连接。。");
            //localhost是本机计算机的ip地址，也可以用命令指令符输入ipconfig查看本机ip地址
            socket =new Socket("localhost",8088);
            System.out.println("连接完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public  void start(){
        try {
            OutputStream out =socket.getOutputStream();
            OutputStreamWriter osw =new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter ow =new BufferedWriter(osw);
            PrintWriter pw =new PrintWriter(ow,true);
            Scanner scan = new Scanner(System.in);
            String str =scan.nextLine();
            while (!"exit".equals(str)){
                pw.println(str);
                str= scan.nextLine();

            }


        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Client client =new Client();
        client.start();
    }

}
